//
//  MTPubMarkVC.m
//  met
//
//  Created by 李晓俊 on 2019/6/13.
//  Copyright © 2019 李晓俊. All rights reserved.
//

#import "MTPubMarkVC.h"
#import "MTPubMarkCell1.h"
#import "MTPubMarkCell2.h"
#import "MTPubMarkCell3.h"
#import "MTPubMarkCell4.h"
#import "MTPubMarkCell5.h"
#import "WNImagePicker.h"

@interface MTPubMarkVC ()<WNImagePickerDelegate,CLLocationManagerDelegate>
@property (nonatomic,strong) NSMutableArray *dataArr;
@property (nonatomic ,strong) UIAlertController *alert;

@property (nonatomic,assign) NSInteger selectIndex;

@property (nonatomic,strong) NSString *titleStr;
@property (nonatomic,strong) NSString *contentStr;
@property (nonatomic,strong) NSString *tagStr;
@property (nonatomic,strong) NSString *addStr;

@property (nonatomic, assign) CLLocationCoordinate2D coordinate;
@end

@implementation MTPubMarkVC {
    CLLocationManager *manager;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setupTableView:UITableViewStyleGrouped header:NO footer:NO];
//    [self.tableView setFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight-85-BottomHeight)];
    [self wr_setNavBarBackgroundAlpha:0];

    self.tableView.tableFooterView = [UIView new];
    self.tableView.backgroundColor = KWhiteColor;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.dataArr = [NSMutableArray new];
    [self setbottomBut];
    self.view.backgroundColor = KWhiteColor;
    
    
    self.titleStr = @"";
    self.contentStr = @"";
    self.tagStr = @"";
    self.addStr = @"";
    
    [self startLocation];

}

- (void)setbottomBut {
    UIView *bg = [UIView new];
    [self.view addSubview:bg];
    [bg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.bottom.mas_equalTo(-BottomHeight);
        make.height.mas_equalTo(80);
    }];
    
    UIButton *done = [UIButton new];
    [done setTitle:@"发布印记" forState:UIControlStateNormal];
    [bg addSubview:done];
    [done mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(15);
        make.right.mas_equalTo(-15);
        make.height.mas_equalTo(60);
        make.top.mas_equalTo(3);
    }];
    done.titleLabel.font = CLRudeCircleTextFont(18);
    [done setTitleColor:KBlackColor forState:UIControlStateNormal];
    [done setBackgroundColor:KMainColor];
    done.layer.masksToBounds = YES;
    done.layer.cornerRadius = 4.0f;
    [done addTarget:self action:@selector(doneClick) forControlEvents:UIControlEventTouchUpInside];
    
    done.layer.borderWidth = 2;
    done.layer.borderColor = KBlackColor.CGColor;
}
//完成点击了
- (void)doneClick {
    [self.view endEditing:YES];
    if (self.titleStr.length == 0) {
        [self.view maketishiToast:@"请先输入标题"];
        return;
    }
    if (self.contentStr.length == 0) {
        [self.view maketishiToast:@"请先输入内容"];
        return;
    }
    if (self.tagStr.length == 0) {
        [self.view maketishiToast:@"请先输入标签"];
        return;
    }
    if (self.addStr.length == 0) {
        [self.view maketishiToast:@"请先添加位置"];
        return;
    }
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    AccountService *acc = [AccountService getObject];
    acc.httpRequestResultBlock = ^(id data,int code){
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (code == 1) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                NSUserDefaults *dataUser = [NSUserDefaults standardUserDefaults];
                [dataUser setObject:@"1" forKey:@"yinji"];
                [dataUser synchronize];
                
                MTOkTishiView *okView = [[MTOkTishiView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
                okView.content.text = @"恭喜你！印记发布成功\n快去“我的”查看吧 ";
                okView.bgView.backgroundColor = KMainColor;
                okView.goButClick = ^(NSString *  s) {
                    [[NSNotificationCenter defaultCenter] postNotificationName:MTFabuNotification1 object:nil];
                    [self.navigationController popViewControllerAnimated:YES];
                };
                [[UIApplication sharedApplication].keyWindow addSubview:okView];
            });
            
        }else {
            [self.view maketishiToast:data];
        }
    };
    NSString *lat = @"";
    NSString *lng = @"";
    if (self.addStr.length > 0) {
        lat =  [NSString stringWithFormat:@"%f",self.coordinate.latitude] ;
        lng = [NSString stringWithFormat:@"%f",self.coordinate.longitude];
    }
    [acc imprintInsert:self.titleStr content:self.contentStr tab:self.tagStr lat:lat lng:lng address:self.addStr imgArr:self.photoArr];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    // 设置导航栏默认的背景颜色
    [WRNavigationBar wr_setDefaultNavBarBarTintColor:KWhiteColor];
    [WRNavigationBar wr_setDefaultNavBarTitleColor:KBlackColor];
    [WRNavigationBar wr_setDefaultNavBarShadowImageHidden:YES];
    [UIApplication sharedApplication].statusBarHidden = NO;
}



#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 5;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        return 100.0f;
    }else if (indexPath.row == 1) {
        return 42.0f;
    }else if (indexPath.row == 2) {
        return 110.0f;
    }
    return 60.0f;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        MTPubMarkCell1 *cell = [MTPubMarkCell1 cellWithTableView:tableView];
        cell.imgArr = self.photoArr;
        
        cell.imgaddClick = ^(NSInteger num) {
            [self.view endEditing:YES];
            if (self.photoArr.count==9) {
                [[UIApplication sharedApplication].keyWindow maketishiToast:@"最多选择9张" ];
                return ;
            }
            WNImagePicker *pickerVC  = [[WNImagePicker alloc] initWithNibName:@"WNImagePicker" bundle:[NSBundle mainBundle]];
            pickerVC.ar = self.photoArr;
            pickerVC.delegate = self;
            UINavigationController *navVC = [[UINavigationController alloc]initWithRootViewController:pickerVC];
            [navVC.navigationBar setBackgroundImage:[UIImage imageWithColor:KBlackColor] forBarPosition:UIBarPositionAny
                                                             barMetrics:UIBarMetricsDefault];
//            [navVC.navigationBar setShadowImage:[UIImage new]];
//            navVC.navigationBar.barTintColor = KWhiteColor;
            navVC.navigationBar.translucent = NO;
            // 设置导航栏默认的背景颜色
            [WRNavigationBar wr_setDefaultNavBarBarTintColor:KBlackColor];
            // 设置导航栏所有按钮的默认颜色
            [WRNavigationBar wr_setDefaultNavBarTitleColor:KWhiteColor];
            
            [self presentViewController:navVC animated:YES completion:nil];
        };
        
        cell.imgClick = ^(NSInteger num) {
            [self.view endEditing:YES];
            self.selectIndex = num;
            [self deletePhoto];
        };
        return cell;
    }else if (indexPath.row == 1) {
        MTPubMarkCell2 *cell = [MTPubMarkCell2 cellWithTableView:tableView];
        cell.titileTF.text = self.titleStr;
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(titleChanged:)
                                                    name:@"UITextFieldTextDidChangeNotification" object:cell.titileTF];
        return cell;
    }else if (indexPath.row == 2) {
        MTPubMarkCell3 *cell = [MTPubMarkCell3 cellWithTableView:tableView];
        cell.contentTV.text = self.contentStr;
        if (self.contentStr.length > 0) {
            cell.contentTV.placehText = @"";
        }else {
            cell.contentTV.placehText = @"说说此刻的心情...";
        }
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(tvChanged:)
                                                    name:@"UITextViewTextDidChangeNotification" object:cell.contentTV];
        return cell;
    }else if (indexPath.row == 3) {
        MTPubMarkCell4 *cell = [MTPubMarkCell4 cellWithTableView:tableView];
        cell.titleTF.text = self.tagStr;
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(title2Changed:)
                                                    name:@"UITextFieldTextDidChangeNotification" object:cell.titleTF];
        return cell;
    }else  {
        MTPubMarkCell5 *cell = [MTPubMarkCell5 cellWithTableView:tableView];
        if (self.addStr.length > 0) {
            cell.titleTF.text = self.addStr;
        }else {
            cell.titleTF.text = @"";
        }
        return cell;
    }
}
-(void)tvChanged:(NSNotification *)obj {
    UITextView *textField = (UITextView *)obj.object;
    self.contentStr = textField.text;
}
-(void)titleChanged:(NSNotification *)obj {
    UITextField *textField = (UITextField *)obj.object;
    self.titleStr = textField.text;
}
-(void)title2Changed:(NSNotification *)obj {
    UITextField *textField = (UITextField *)obj.object;
    self.tagStr = textField.text;
}
- (void)deletePhoto {
    [self.view endEditing:YES];

    if (self.photoArr.count == 1) {
        return;
    }
    if (!self.alert) {
        self.alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        UIAlertAction *paizhao =[UIAlertAction actionWithTitle:@"删除照片" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
            [self.photoArr removeObjectAtIndex:self.selectIndex];
            [self.tableView  reloadData];
        }];
//        [paizhao setValue:KBlackColor forKey:@"_titleTextColor"];
        [self.alert addAction:paizhao];
        UIAlertAction *cancle = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        }];
//        [cancle setValue:KBlackColor forKey:@"_titleTextColor"];
        [self.alert addAction:cancle];
    }
    
    [self presentViewController:self.alert animated:true completion:nil];
}
#pragma mark -- WNImagePickerDelegate
- (void)getCutImage:(NSMutableArray *)imageArr controller:(WNImagePicker *)vc
{
    [vc.navigationController dismissViewControllerAnimated:NO completion:nil];
    [self.photoArr addObjectsFromArray:imageArr];
    [self.tableView reloadData];
}

- (void)onCancel:(WNImagePicker *)vc
{
    [vc.navigationController dismissViewControllerAnimated:YES completion:nil];
}


-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.01f;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *v = [UIView new];
    return v;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01f;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *view = [UIView new];
    return view;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 4) {
        //选择位置
        [self startLocation];
     }
}
//开始定位
-(void)startLocation{
    manager = [[CLLocationManager alloc]init];
    manager.delegate = self;
    manager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;//精准度
    manager.distanceFilter = 1.0;
    [manager startUpdatingLocation];
}

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
    CLLocation *loctaion = [locations firstObject];
    self.coordinate = loctaion.coordinate;
    [manager stopUpdatingLocation];
    CLGeocoder *geocoder = [[CLGeocoder alloc]init];
    [geocoder reverseGeocodeLocation:loctaion completionHandler:^(NSArray<CLPlacemark *> *_Nullable placemarks, NSError * _Nullable error) {
        for (CLPlacemark *place in placemarks) {
            self.addStr = [NSString stringWithFormat:@"%@%@",place.subLocality,place.thoroughfare];
//            ,place.
            NSIndexPath *indexPath=[NSIndexPath indexPathForRow:4 inSection:0];
            [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
        }
    }];
}
@end
